<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>课堂练习</title>
    <link rel="stylesheet" href="style.css">
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        .container {
            max-width: 900px;
            margin: 0px auto;
        }

        .header h1 {
            font-size: 22px;
            text-align: center;
        }

        .question-section {
            margin-bottom: 32px;
        }

        .question {
            margin-bottom: 18px;
        }

        .question-number {
            font-weight: bold;
            margin-right: 6px;
        }

        .options {
            margin: 8px 0 0 0;
        }

        .option {
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .option label:hover {
            cursor: pointer;
        }

        .option.correct label {
            color: #1976d2;
            font-weight: bold;
        }

        .option.incorrect label {
            color: #e74c3c;
        }

        .btn-group {
            margin: 24px 0 0 0;
            text-align: center;
        }

        .btn {
            padding: 8px 24px;
            border-radius: 4px;
            border: none;
            font-size: 16px;
            margin: 0 8px;
            cursor: pointer;
        }

        .btn-primary {
            background: #1976d2;
            color: #fff;
        }

        .btn-primary:hover {
            background: #1565c0;
        }

        .btn-secondary {
            background: #eee;
            color: #333;
        }

        .btn-secondary:hover {
            background: #ddd;
        }

        .result {
            display: none;
            margin-top: 24px;
            text-align: center;
        }

        .result.show {
            display: block;
        }

        .correct-answer {
            color: #388e3c;
            margin-top: 4px;
        }

        .explanation {
            color: #888;
            font-size: 14px;
            display: none;
            margin-top: 2px;
        }

        .explanation.show {
            display: block;
        }

        .short-answer {
            width: 95%;
            min-height: 60px;
            font-size: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 6px;
            margin: 8px 0;
            resize: vertical;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>课堂练习</h1>
        </div>
        <div class="card"></div>
    </div>
    <script>
        // 题库
        const questions = [
            {
                type: 'judge',
                section: '一、判断题',
                items: [
                    {
                        text: '互联网在形成阶段实现了TCP/IP协议的标准化。',
                        options: [{ value: 'A', label: '正确' }, { value: 'B', label: '错误' }],
                        answer: 'B',
                        explanation: 'TCP/IP协议标准化是在互联阶段实现的，形成阶段的标志是阿帕网（ARPA Net）诞生。'
                    }
                ]
            },
            {
                type: 'single',
                section: '二、单项选择题',
                items: [
                    {
                        text: '互联网发展的哪个阶段实现了TCP/IP协议标准化？',
                        options: [
                            { value: 'A', label: '诞生阶段' },
                            { value: 'B', label: '形成阶段' },
                            { value: 'C', label: '互联阶段' },
                            { value: 'D', label: '高速网络阶段' }
                        ],
                        answer: 'C',
                        explanation: '在互联阶段，TCP/IP协议实现标准化，成为互联网的基础协议。'
                    }
                ]
            },
            {
                type: 'multi',
                section: '三、多项选择题',
                items: [
                    {
                        text: '下列哪些属于互联网基础协议？（多选）',
                        options: [
                            { value: 'A', label: 'TCP' },
                            { value: 'B', label: 'IP' },
                            { value: 'C', label: 'HTTP' },
                            { value: 'D', label: 'SMTP' }
                        ],
                        answer: ['A', 'B', 'D'],
                        explanation: 'TCP、IP、SMTP 都是互联网基础协议，HTTP 属于应用层协议。'
                    }
                ]
            },
            {
                type: 'short',
                section: '四、简答题',
                items: [
                    {
                        text: '请简述互联网发展的四个阶段。',
                        reference: '诞生阶段、形成阶段、互联阶段、高速网络阶段。',
                        explanation: '互联网发展经历了诞生、形成、互联和高速网络四个阶段。'
                    }
                ]
            }
        ];

        // 自动生成 number 字段
        (function autoNumberQuestions() {
            let num = 1;
            questions.forEach(section => {
                section.items.forEach(item => {
                    item.number = num++;
                });
            });
        })();

        // 渲染题目
        function renderQuestions() {
            const card = document.querySelector('.card');
            card.innerHTML = `
                <div class="progress">
                    进度：<span id="current">0</span>/${questions.reduce((sum, sec) => sum + sec.items.length, 0)}题
                </div>
                <div id="questions"></div>
                <div class="btn-group">
                    <button class="btn btn-primary" id="submit">提交答案</button>
                    <button class="btn btn-secondary" id="reset">重置</button>
                </div>
                <div class="result" id="result">
                    <h3 class="correct">答题完成！共答对 <span id="score">0</span> 题</h3>
                </div>
            `;
            const questionsDiv = card.querySelector('#questions');
            let html = '';
            questions.forEach(section => {
                html += `<div class="question-section"><h2 class="section-title">${section.section}</h2>`;
                section.items.forEach(item => {
                    let name;
                    if (section.type === 'judge') {
                        name = `t${item.number}`;
                        html += `
                            <div class="question">
                                <p><span class="question-number">${item.number}</span>${item.text}</p>
                                <div class="options">
                                    ${item.options.map(opt => `
                                        <div class="option">
                                            <input type="radio" name="${name}" value="${opt.value}" id="${name}-${opt.value}">
                                            <label for="${name}-${opt.value}">${opt.value}. ${opt.label}</label>
                                        </div>
                                    `).join('')}
                                </div>
                                <div class="correct-answer" id="ans-${name}"></div>
                                <div class="explanation" id="exp-${name}">解析：${item.explanation}</div>
                            </div>
                        `;
                    } else if (section.type === 'single') {
                        name = `q${item.number}`;
                        html += `
                            <div class="question">
                                <p><span class="question-number">${item.number}</span>${item.text}</p>
                                <div class="options">
                                    ${item.options.map(opt => `
                                        <div class="option">
                                            <input type="radio" name="${name}" value="${opt.value}" id="${name}-${opt.value}">
                                            <label for="${name}-${opt.value}">${opt.value}. ${opt.label}</label>
                                        </div>
                                    `).join('')}
                                </div>
                                <div class="correct-answer" id="ans-${name}"></div>
                                <div class="explanation" id="exp-${name}">解析：${item.explanation}</div>
                            </div>
                        `;
                    } else if (section.type === 'multi') {
                        name = `m${item.number}`;
                        html += `
                            <div class="question">
                                <p><span class="question-number">${item.number}</span>${item.text}</p>
                                <div class="options">
                                    ${item.options.map(opt => `
                                        <div class="option">
                                            <input type="checkbox" name="${name}" value="${opt.value}" id="${name}-${opt.value}">
                                            <label for="${name}-${opt.value}">${opt.value}. ${opt.label}</label>
                                        </div>
                                    `).join('')}
                                </div>
                                <div class="correct-answer" id="ans-${name}"></div>
                                <div class="explanation" id="exp-${name}">解析：${item.explanation}</div>
                            </div>
                        `;
                    } else if (section.type === 'short') {
                        name = `s${item.number}`;
                        html += `
                            <div class="question">
                                <p><span class="question-number">${item.number}</span>${item.text}</p>
                                <textarea name="${name}" rows="3" class="short-answer"></textarea>
                                <div class="correct-answer" id="ans-${name}"></div>
                                <div class="explanation" id="exp-${name}">参考答案：${item.reference}<br>解析：${item.explanation}</div>
                            </div>
                        `;
                    }
                });
                html += '</div>';
            });
            questionsDiv.innerHTML = html;
        }
        renderQuestions();

        // 生成正确答案映射
        const correctAnswers = {};
        questions.forEach(section => {
            section.items.forEach(item => {
                let name;
                if (section.type === 'judge') {
                    name = `t${item.number}`;
                    correctAnswers[name] = item.answer;
                } else if (section.type === 'single') {
                    name = `q${item.number}`;
                    correctAnswers[name] = item.answer;
                } else if (section.type === 'multi') {
                    name = `m${item.number}`;
                    correctAnswers[name] = item.answer;
                } else if (section.type === 'short') {
                    name = `s${item.number}`;
                    correctAnswers[name] = item.reference;
                }
            });
        });

        // 获取DOM元素
        const card = document.querySelector('.card');
        const currentEl = card.querySelector("#current");
        const scoreEl = card.querySelector("#score");
        const resultEl = card.querySelector("#result");

        // 更新进度
        function updateProgress() {
            let count = 0;
            for (const name of Object.keys(correctAnswers)) {
                if (name.startsWith('s')) {
                    // 简答题：有内容即算已答
                    const ta = card.querySelector(`textarea[name="${name}"]`);
                    if (ta && ta.value.trim() !== "") count++;
                } else {
                    const inputType = Array.isArray(correctAnswers[name]) ? 'checkbox' : 'radio';
                    if (inputType === 'radio') {
                        if (card.querySelector(`input[name="${name}"]:checked`)) count++;
                    } else {
                        if (card.querySelectorAll(`input[name="${name}"]:checked`).length > 0) count++;
                    }
                }
            }
            currentEl.textContent = count;
        }

        // 验证答案并计算得分
        function validateAnswers() {
            let score = 0;
            for (const [question, answer] of Object.entries(correctAnswers)) {
                const ansEl = card.querySelector(`#ans-${question}`);
                const expEl = card.querySelector(`#exp-${question}`);
                if (question.startsWith('m')) {
                    // 多选题
                    const selected = Array.from(card.querySelectorAll(`input[name="${question}"]:checked`)).map(i => i.value).sort();
                    const correct = answer.slice().sort();
                    ansEl.textContent = `正确答案：${correct.join('、')}`;
                    expEl.classList.add('show');
                    correct.forEach(val => {
                        const opt = card.querySelector(`input[name="${question}"][value="${val}"]`);
                        if (opt) opt.closest('.option').classList.add('correct');
                    });
                    selected.forEach(val => {
                        if (!correct.includes(val)) {
                            const opt = card.querySelector(`input[name="${question}"][value="${val}"]`);
                            if (opt) opt.closest('.option').classList.add('incorrect');
                        }
                    });
                    if (selected.length && selected.join(',') === correct.join(',')) {
                        score++;
                    }
                } else if (question.startsWith('s')) {
                    // 简答题
                    const userInput = card.querySelector(`textarea[name="${question}"]`).value.trim();
                    ansEl.textContent = `参考答案：${answer}`;
                    expEl.classList.add('show');
                    // 简答题不自动判分
                } else {
                    // 单选/判断题
                    const selectedOption = card.querySelector(`input[name="${question}"]:checked`);
                    ansEl.textContent = `正确答案：${answer}`;
                    expEl.classList.add('show');
                    const correctOption = card.querySelector(`input[name="${question}"][value="${answer}"]`);
                    if (correctOption) correctOption.closest('.option').classList.add('correct');
                    if (selectedOption) {
                        if (selectedOption.value === answer) {
                            score++;
                        } else {
                            selectedOption.closest('.option').classList.add('incorrect');
                        }
                    }
                }
            }
            scoreEl.textContent = score;
            resultEl.classList.add('show');
        }

        // 重置答题状态
        function resetQuiz() {
            // 清除选中状态和样式
            card.querySelectorAll('input[type="radio"],input[type="checkbox"]').forEach(input => {
                input.checked = false;
                const optionEl = input.closest('.option');
                if (optionEl) optionEl.classList.remove('correct', 'incorrect');
            });
            card.querySelectorAll('.short-answer').forEach(ta => {
                ta.value = '';
            });
            // 隐藏正确答案、解析和结果
            Object.keys(correctAnswers).forEach(question => {
                const ansEl = card.querySelector(`#ans-${question}`);
                const expEl = card.querySelector(`#exp-${question}`);
                if (ansEl) ansEl.textContent = "";
                if (expEl) expEl.classList.remove('show');
            });
            resultEl.classList.remove('show');
            updateProgress();
        }

        // 监听选项变化
        card.addEventListener('change', function (e) {
            if (
                e.target.type === 'radio' ||
                e.target.type === 'checkbox' ||
                e.target.classList.contains('short-answer')
            ) {
                updateProgress();
            }
        });

        // 监听提交按钮
        card.querySelector("#submit").addEventListener('click', validateAnswers);
        // 监听重置按钮
        card.querySelector("#reset").addEventListener('click', resetQuiz);
        // 初始化进度
        updateProgress();
    </script>
</body>

</html>